const express = require("express");
const router = express.Router();
const path = require("path");
const config = require("../../../config/config.default"); //保存全局变量

//加载柜门信息
// const data=require('../../../nndb.json')
const data = require("../../../gldb.json");

//浏览器
const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: false })

router.use("/open/:czh", (req, res) => {
  const czh = req.params["czh"];
  if (!czh) {
    res.status(404).send({ msg: "车组号不能为空", code: 404 });
    return;
  }

  if(!data||!data.locks){
    res.status(500).send({ msg: "门柜信息获取失败", code: 500 });
    return
  }

  const findIndex=data.locks.findIndex(lock=>lock.czh===czh);
  if(findIndex===-1){
    res.status(404).send({ msg: "确认车组号是否存在", code: 404 });
    return
  }

  //执行打开柜门
  nightmare
  .goto('http://localhost/lightmini.html')
  //   .type('#name', 'github nightmare')
    .evaluate(async () => {
      const result=await openDoor(data.locks[findIndex]) //调用html页面的异步异步
      return result
    })
    .end()
    .then((msg)=>{
      res.send({ msg: "ok", code: 200,data:msg });
    })
    .catch(error => {
        res.status(500).send({ msg: "err", code: 500,data:error });
    })
});


module.exports = router;
